/*
 * Copyright (c) 2011, 2012 Alexander Kluth <alexander.kluth@outlook.com>
 * 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package hardyhttp.filesystem;

import java.io.*;
import java.util.*;
import java.text.*;

/**
 * Simple class for logging.
 * 
 * @author akluth
 */
public class Logger
{
    File logfile;
    FileWriter write;
    Date date = new Date();
    
    // Used for the logentries
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    
    // Used for the filename
    SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmssS");
    
    // #defines for the level 
    public static final int LOG_STDOUT = 1;
    public static final int LOG_FILE = 2;
    
    // Defines where to log
    private int level = 0;
    
    // Indicates if the logfile is created or not
    boolean logfilecreated;
    
    
    /**
     * C'tor, sets the level of logging and creates a logfile, if wanted
     * 
     * @param level 
     */
    public Logger(int level)
    {
        this.level = level;
        
        if (level == LOG_FILE)
        {
            createLogFile();
        }
    }
    
    
    /**
     * Create the logfile
     */
    public void createLogFile()
    {
        try
        {
            // Create a logfile with date- and timestamp
            logfile = new File("logs" + File.separator + "httpd-" + fileDateFormat.format(date) + ".txt");
            write = new FileWriter(logfile);
            logfilecreated = true;
        }
            
        catch (IOException ioe)
        {
            // When an error occurs set everything to stdout and inform the user
            logfilecreated = false;
            setLogLevel(LOG_STDOUT);
            System.out.println("[LOGGER] Error creating logfile: " + ioe.getMessage());
            System.out.println("[LOGGER] All following output will go to STDOU");
        }
    }
    
    
    /**
     * Java DO NEED some get/set functionality
     * 
     * @returns true if file exist, false otherwise
     */
    public boolean logFileExist()
    {
        return logfilecreated;
    }
    
    
    /**
     * Set loglevel
     * 
     * @param level Loglevel
     */
    public boolean setLogLevel(int level)
    {
        //TODO: Hm...I could use some self created exception-classes,
        //      so I can have more granularity when an error occures.
        //      But I don't like try-catch-Statements, so...;-)
        
        if (level > LOG_FILE || logfilecreated)
        {
            return false;
        }
        
        else if (level == LOG_FILE && !logfilecreated)
        {
            this.level = level;
            createLogFile();
            return true;
        }
        
        else if (level == LOG_STDOUT)
        {
            this.level = level;
            return true;
        }
        
        return false;
    }
    
    /**
     * Logs a event either to stdout or to a logfile
     * 
     * @param eventstring 
     */
    public void logEvent(String eventstring) 
    {
        if (level == LOG_STDOUT)
        {
            System.out.println(eventstring); 
        }
        
        else
        {
            try
            {
                write.append(dateformat.format(date) + " " + eventstring + System.getProperty("line.separator")); // \n
                write.flush(); //! VERY important because otherwise there data will NOT be written to the file!
            }
            
            catch (IOException ioe)
            {
                System.out.println("\n[LOGGER] Error while writing to logfile!");
                System.exit(-1);
            }
        }
    }
    
    
    // Figured out that under Windows 7 this is quite important, that we have to close
    // the file properly when exiting the webserver
    @Override
    protected void finalize() throws IOException, Throwable
    {
        write.close();
        super.finalize();
    }
}
